﻿using AutoMapper;
using BW.MesProject.Production.Domain.Dto.Input.WorkProcess;
using BW.MesProject.Production.Domain.Dto.Output.WorkProess;
using BW.MesProject.Production.Domain.Model;
using BW.MesProject.Production.Infrastructure;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using BW.MesProject.WareHouse.Domain;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BW.MesProject.Production.Application
{
    public class WorkProcessServices : IWorkProcessServices
    {
        private readonly IBaseRepository<WORKPROESSMODEL> _workProessRepository;
        private readonly IMapper _mapper;
        private readonly IBaseRepository<PRODUCTIONREPORT> _productionReporRepository;
        private readonly IBaseRepository<ProcessManagModel> _ProcessManagRepostiory;
        private readonly IBaseRepository<WORKORDERMODEL> _workOrderReposiroy;
        public WorkProcessServices(IBaseRepository<WORKPROESSMODEL> workProessRepository, IMapper mapper, IBaseRepository<PRODUCTIONREPORT> productionReporRepository, IBaseRepository<ProcessManagModel> processManagRepostiory, IBaseRepository<WORKORDERMODEL> workOrderReposiroy)
        {
            _workProessRepository = workProessRepository;
            _mapper = mapper;
            _productionReporRepository = productionReporRepository;
            _ProcessManagRepostiory = processManagRepostiory;
            _workOrderReposiroy = workOrderReposiroy;
        }

        public ApiResult<int> UpdateWorkProess(WorkPorcessInput input)
        {
            // 添加事务处理
            var db = _workProessRepository.GetAll().Context;  // 获取SqlSugarClient
            try
            {
                db.Ado.BeginTran();
                var proess = _workProessRepository.GetValue(x => x.ID == input.ID);
                if (proess == null)
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Error,
                        Message = "未找到对应工序",
                        Data = 0
                    };
                }
                proess = _mapper.Map(input, proess);
                proess.NUM += input.NUM;
                if (proess.NUM > proess.SUM)
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Error,
                        Message = "报工数量不能大于总数",
                        Data = 0
                    };
                }

                proess.NONUM += input.NONUM;
                proess.ISSTART = false;
                if (proess.NUM >= proess.SUM)
                {
                    proess.ISSTATE = true;
                    var proess2 = _workProessRepository.GetAll().First(x => x.WORKORDERCODE == proess.WORKORDERCODE && x.INDEX == (proess.INDEX + 1));
                    if (proess2 != null)
                    {
                        proess2.ISSHOW = true;
                        _workProessRepository.Update(proess2);
                    }
                }
                _workProessRepository.Update(proess);

                var workorder = _workOrderReposiroy.GetAll().First(x => x.WORKORDERCODE == proess.WORKORDERCODE);
                var processs = _workProessRepository.GetAll().Where(x => x.WORKORDERCODE == workorder.WORKORDERCODE).ToList();
                decimal? znum = 0;
                decimal? num = 0;
                decimal? nonum = 0;
                decimal? sum = 0;
                for (int i = 0; i < processs.Count(); i++)
                {
                    znum += (long)processs[i].NUM! + (long)processs[i].NONUM!;
                    num += processs[i].NUM!;
                    nonum += (long)processs[i].NONUM!; 
                    sum += processs[i].SUM!;
                    workorder.UPDATETIME = DateTime.Now;
                }
                workorder.GOODNUM = (long)num;
                workorder.FAILNUM = (long)num;
                workorder.QUANTITYNUM = (long)znum;
                workorder.COMPLETEDNUM = (long)num;
                decimal? sorce = num / sum;
                workorder.PROGRESS = sorce.ToString()+"%";
                _workOrderReposiroy.Update(workorder);

                PRODUCTIONREPORT productionRepor = new PRODUCTIONREPORT()
                {
                    PRODUCTIONREPORCODE = "PR" + DateTime.Now.ToString("yyyyMMdd") + new Random().Next(1000, 9999).ToString(),
                    DATETIME = DateTime.Now,
                    WORKORDERCODE = proess.WORKORDERCODE,
                    PRODUCTIONPROCESSESCODE = proess.PMID,
                    PRODUCTIONPROCESSESNAME = proess.PMNAME,
                    PRODUCTNAME = input.ProductName,
                    PRODUCTIONSTAFF = "admin",
                    PRODUCTIONTIME = input.PRODUCTIONTIME,
                    REPORTQUANTITY = input.NUM + input.NONUM,
                    QUALIFIEDQUANTITY = input.NUM,
                    UNQUALIFIEDQUANTITY = input.NONUM,
                    CREATEBY = "admin",
                    CREATETIME = DateTime.Now,
                    ISDELETED = false,
                    PRODUCTCODE = workorder.PRODUCTMASTERDATAID.ToString(),
                };
                _productionReporRepository.Add(productionRepor);

                
                db.Ado.CommitTran(); 
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Message = "新增产出成功",
                    Data = 1
                };
            }
            catch (Exception ex)
            {
                db.Ado.RollbackTran();
                throw ex;
            }
            
        }

        public ApiResult<List<WorkProessOutput>> GetWorkProessList(string WorkOrderCode)
        {
            var workproesss = _workProessRepository.GetAll().Where(x => x.NUM != x.SUM && x.ISSHOW==true && x.ISSTATE ==false && x.WORKORDERCODE==WorkOrderCode).ToList();
            var output = _mapper.Map<List<WorkProessOutput>>(workproesss);
            return new ApiResult<List<WorkProessOutput>>()
            {
                Code = ApiEnums.Success,
                Message = "查询成功",
                Data = output,
            };
        }

        public ApiResult<WorkProessOutput> GetWorkProess(decimal Id)
        {
            var workproess = _workProessRepository.GetValue(x => x.ID == Id);
            var output = _mapper.Map<WorkProessOutput>(workproess);

            if(output==null)
            {
                return new ApiResult<WorkProessOutput>()
                {
                    Code = ApiEnums.Error,
                    Data = new WorkProessOutput(),
                    Message = "查询失败"
                };
            }

            return new ApiResult<WorkProessOutput>()
            {
                Code = ApiEnums.Success,
                Data = output,
                Message = "查询成功"
            };
        }

        public ApiResult<int> StartWorkProess(string DateTime,decimal Id)
        {
            var workproess = _workProessRepository.GetValue(x=>x.ID== Id);
            if(workproess.ISSTART==true)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Error,
                    Message = "工序已开始",
                    Data = 0
                };
            }
            workproess.ISSTART = true;
            workproess.DATETIME = DateTime;
            int r = _workProessRepository.Update(workproess);

            if(r>0)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Message = "工序开始",
                    Data = r
                };
            }
            return new ApiResult<int>()
            {
                Code = ApiEnums.Error,
                Message = "工序开始失败",
                Data = r
            };

        }
        public ApiResult<List<WORKPROESSMODEL>> GetWorkProesss()
        {
            var list = _workProessRepository.GetAll();
            return new ApiResult<List<WORKPROESSMODEL>>()
            {
                Data = list.ToList(),
                Code = ApiEnums.Success,
                Message = "获取成功",
                TotalCount = list.Count()
            };
        }
    }
}
